package second_assignment;

import java.util.HashMap;

/**
 * a type definition for the disk structure.
 * implementing basic disk functionality.
 * 
 * @author Peretz Oded, Castel Maayan, Farchy Ofir.
 */
public class DiskType {
	
	// keeps track of the current number of stream lines avail.
	private int numberOfStreamsLeft;

	// keeps track of the current number of movies in the list.
	private int numberOfMovies;

	// disk's movie list, holds information on movies currently being watched.
	private HashMap<String, Integer> movieList;
	
	/**
	 * c'tor
	 * @param streamLines - number of concurrent stream lines available for usage.
	 */
	public DiskType(int streamLines) {
		numberOfStreamsLeft = streamLines;
		numberOfMovies = 0;
		movieList = new HashMap<String, Integer>();
	}

	/**
	 * adds a new movie to the list, unless already in the list.
	 * @param movieId - the movie identifier (unique)
	 * @return success indicator.
	 */
	public Boolean AddMovie(String movieId) {
		if (Consts_2nd.DiskCapacity > numberOfMovies) {
			if (!movieList.containsKey(movieId)) {
				movieList.put(movieId, 0);
				++numberOfMovies;
				return true;
			}
		}
		return false;
	}

	/**
	 * marks a given movie as occupied (being used by a client)
	 * @param movieId - the movie to occupy.
	 * @return success indicator.
	 */
	public Boolean OccupyMovie(String movieId) {
		if ((0 < numberOfStreamsLeft) && (movieList.containsKey(movieId))) {
			movieList.put(movieId, movieList.get(movieId) + 1);
			--numberOfStreamsLeft;
			return true;
		}
		return false;
	}

	/**
	 * clears the given movie for further client use 
	 * @param movieId - the movie to clear status for.
	 */
	public void ReleaseMovie(String movieId) {
		if (movieList.containsKey(movieId) && (movieList.get(movieId) != 0)) {
		    numberOfStreamsLeft++;
		    movieList.put(movieId, movieList.get(movieId) - 1);
		}
	}

	public int AmountOfCopies() {
		return numberOfMovies;
	}
	
	public boolean DeleteMovie(String movieName){
	    if (movieList.containsKey(movieName)) {
	        if (movieList.get(movieName) != 0)
	            return false;
    		if (null != movieList.remove(movieName)) { 
    			--numberOfMovies;
    			return true;
    		}
	    }
		return false;
	}

	public boolean Contains(String movieName) {
		return movieList.containsKey(movieName);
	}

	public String getUniqueMovie(DiskType disk) {
		for (String movieName : movieList.keySet()) {
			if ((movieList.get(movieName) == 0) && !disk.Contains(movieName)) {
				return movieName;
			}
		}
		return null;
	}

    public int NumberOfStreamsLeft() {
        return numberOfStreamsLeft;
    }
}
